<!--
 * @Author: your name
 * @Date: 2021-02-05 14:52:13
 * @LastEditTime: 2021-08-27 12:36:40
 * @LastEditors: dailuyu
 * @Description: In User Settings Edit
 * @FilePath: \TaskErrorManage\src\views\layoutpages\system\Project.vue
-->
<template>
  <div class="ve_container">
    <!-- 搜索 -->
    <el-form ref="queryForm" :inline="true" :model="params">
      <el-form-item label="名称" prop="temp">
        <el-input clearable v-model="temp" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(params, queryProject(temp))">
          {{ menus.search.name }}
        </el-button>
        <el-button @click="resetForm(queryForm, params, getDataList)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- table工具条 -->
    <el-row ref="toolBar" class="ve_header_row_class_name ve_p_10">
      <el-button
        title="弹窗式"
        v-permission="['add']"
        size="mini"
        type="primary"
        @click="handleEdit(menus.add.name)"
      >
        {{ menus.add.name }}
      </el-button>
    </el-row>
    <!-- 列表 -->
    <el-table
      :data="tableData"
      stripe
      border
      row-key="Id"
      lazy
      :load="load"
      v-bind:fData="IsHidden"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      :row-class-name="({ rowIndex }) => rowClassName(rowIndex, ve_rowIndex)"
      :cell-class-name="({ rowIndex }) => cellClassName(rowIndex, ve_rowIndex)"
      header-row-class-name="ve_header_row_class_name"
      header-cell-class-name="ve_header_cell_class_name"
      style="width: 100%"
      :max-height="ve_max_height"
      @row-dblclick="rowDbclick"
    >
      <!-- <el-table-column prop="Id" label="标识"> </el-table-column>
            <el-table-column prop="FId" label="父级标识"> </el-table-column> -->
      <el-table-column prop="Name" label="名称"></el-table-column>
      <el-table-column prop="UserId" label="创建人Id"></el-table-column>
      <el-table-column prop="CreateDate" label="创建时间"></el-table-column>
      <el-table-column prop="Remark" label="描述"></el-table-column>
      <el-table-column prop="IsUse" label="是否启用">
        <template v-slot="{ row }">
          <el-switch
            :loading="row.load ? true : false"
            v-model="row.IsUse"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="val => handelSwitch(val, row)"
          >
            >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template v-slot:default="{ row }">
          <el-button
            @click.prevent="handleEdit(menus.edit.name, row)"
            type="primary"
            size="mini"
          >
            {{ menus.edit.name }}
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDel(row.FId, row.Id)"
          >
            {{ menus.del.name }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      ref="pagination"
      background
      @size-change="val => handleSizeChange(val, params, getDataList)"
      @current-change="val => handleCurrentChange(val, params, getDataList)"
      :hide-on-single-page="total <= limit ? true : false"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="page"
      :page-size="limit"
      :total="total"
    ></el-pagination>

    <!-- 编辑组件 -->
    <ProjectEdit
      v-if="showDialog"
      :rowData="rowData"
      :title="dialogTitle"
      :showDialog="showDialog"
      :isHidden="IsHidden"
      :ButtonHidden="ButtonHidden"
      :tableData="tableData"
      @searchClick="searchClick"
      @editClick="editClick"
      @closeDialog="handelDialog($event)"
    />
  </div>
</template>

<script>
import ProjectEdit from "./components/ProjectEdit"
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from "vue"
import { useRoute, useRouter } from "vue-router"
import {
  AddProject,
  DeleteProject,
  EditProject,
  GetProject,
} from "@/api/projectManage"

//?导入公共查询方法
import {
  onSubmit,
  handleSizeChange,
  handleCurrentChange,
  rowClassName,
  cellClassName,
  rowClick,
  maxHeight,
  getAsyncRouteName,
} from "@/views/layoutpages/common"
export default {
  methods: {
    getCurrentTime() {
      //构建方法
      var today = new Date() //new 出当前时间
      var h = today.getFullYear() //获取年
      var m = today.getMonth() + 1 //获取月
      var d = today.getDate() //获取日
      var H = today.getHours() //获取时
      var M = today.getMinutes() //获取分
      var S = today.getSeconds() //获取秒
      return h + "-" + m + "-" + d + " " + H + ":" + M + ":" + S //返回 年-月-日 时:分:秒
    },
    rowDbclick(row, event, column) {
      this.rowData = row
      console.log(row, column)
      this.showDialog = true
      this.ButtonHidden = false
    },
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve([
          {
            id: 31,
            date: "2016-05-01",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1519 弄",
          },
          {
            id: 32,
            date: "2016-05-01",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1519 弄",
          },
        ])
      }, 1000)
    },
  },
  data: () => ({
    description: "用户信息查询与设置",
    DialogVisible: false,
    editDialog: false,
    response: [],
    temp: "",
    origindata: [],
    //isHidden: false,
    menus: {
      search: { name: "查询" },
      add: { name: "添加" },
      edit: { name: "编辑" },
      del: { name: "删除" },
    },
    options: [
      {
        value: "选项1",
        label: "1.普通",
      },
      {
        value: "选项2",
        label: "2.高",
      },
      {
        value: "选项3",
        label: "3.紧急",
      },
      {
        value: "选项4",
        label: "4.立刻",
      },
    ],
    value: "",
  }),
  components: {
    ProjectEdit,
  },
  setup() {
    const IsHidden = ref(false)
    const ButtonHidden = ref(true)
    const { proxy } = getCurrentInstance()
    const route = useRoute()
    const router = useRouter()
    const rowData = ref(null)
    const dialogTitle = ref("")
    const showDialog = ref(false)
    const ve_max_height = ref(0)
    const ve_rowIndex = ref(null)
    const toolBar = ref(null)
    const pagination = ref(null)
    const queryForm = ref(null)
    const tableData = ref([])
    const params = reactive({
      name: isNaN(route.query.name * 1) ? "" : route.query.name * 1,
      limit: 10,
      page: 1,
      total: 0,
    })
    const { name, limit, page, total } = toRefs(params)
    const projectList = ref([])

    /**
     * @description:添加or编辑事件
     * @param {*}
     * @return {*}
     */
    const handleEdit = (title, row = null) => {
      dialogTitle.value = title
      if (title == "编辑") {
        // eslint-disable-next-line no-const-assign
        IsHidden.value = false
        rowData.value = row
      } else {
        IsHidden.value = true
      }
      showDialog.value = true
    }
    /**
     * @description: 添加页面路由式
     * @param {*}
     * @return {*}
     */
    const handleEditRoute = async title => {
      let path = "system/components/ProjectEditRoute"
      const toName = await getAsyncRouteName(title, path, "add", {
        router,
        route,
      })
      router.push({ name: toName })
    }
    /**
     * @description: dialog事件
     * @param {*}
     * @return {*}
     */
    const handelDialog = e => {
      showDialog.value = e
    }
    /**
     * @description:用户状态切换
     * @param {*}
     * @return {*}
     */
    const handelSwitch = (val, row) => {
      editClick(row)
      if (row.Id == undefined) return
      row.IsUse = val
    }
    /**删除行数据
     * @description:
     * @param {*}
     * @return {*}
     */
    const handleDel = (tempfid, tempid) => {
      proxy
        .$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        })
        .then(async () => {
          Delete(tempid)
          //         GetProject().then((response) => {
          //      for (var m = 0; m < tableData.value.length; m++) {
          //          if(response.data.data[m].FId==tempid)
          //          {

          //          }
          //      }
          // });
          if (tempfid == 0) {
            for (var p = 0; p < tableData.value.length; p++) {
              if (tableData.value[p].Id == tempid) {
                for (var m = 0; m < tableData.value.length; m++) {
                  Delete(tableData.value[p].children[m].Id)
                }
                tableData.value.splice(p, p + 1)
                tableData.value[p].children.splice(
                  0,
                  tableData.value[p].children.length
                )
              }
            }
          } else {
            for (var i = 0; i < tableData.value.length; i++) {
              if (tableData.value[i].Id == tempfid) {
                tableData.value[i].children.splice(0, 1)
              }
            }
          }
          // .catch(() => {
          //     proxy.$message({
          //         type: "info",
          //         message: "已取消删除",
          //     });
          // });
        })
    }
    /**
     * @description: 获取列表数据
     * @param {*}
     * @return {*}
     */
    const getDataList = () => {
      GetProject().then(response => {
        tableData.value.splice(0, tableData.value.length)
        ChangeTableData(response.data.data)
      })
    }

    const ChangeTableData = data => {
      for (var i = 0; i < data.length; i++) {
        var _data = {
          CreateDate: "",
          FId: "",
          Id: "",
          IsDelete: 0,
          IsUse: 0,
          Name: "",
          Remark: "",
          UserId: "",
          children: [],
        }
        _data.CreateDate = data[i].CreateDate
        _data.FId = data[i].FId
        _data.Id = data[i].Id
        _data.IsDelete = data[i].IsDelete
        _data.IsUse = data[i].IsUse
        _data.Name = data[i].Name
        _data.Remark = data[i].Remark
        _data.UserId = data[i].UserId
        if (_data.FId == 0 && _data.IsDelete == 0) {
          tableData.value.push(_data)
        }
      }
      for (var n = 0; n < data.length; n++) {
        for (var p = 0; p < tableData.value.length; p++) {
          if (
            tableData.value[p].Id == data[n].FId &&
            data[n].FId != 0 &&
            data[n].IsDelete == 0
          ) {
            tableData.value[p].children.push(data[n])
          }
        }
      }
    }
    const queryProject = Name => {
      var condition = true
      for (var i = 0; i < tableData.value.length; i++) {
        if (Name == tableData.value[i].Name) {
          var tempdata = tableData.value[i]
          tableData.value.splice(0, tableData.value.length)
          tableData.value.push(tempdata)
          condition = false
          break
        }
      }
      if (condition) {
        tableData.value.splice(0, tableData.value.length)
      }
    }
    const Delete = async Id => {
      DeleteProject(Id).then(response => {
        if (response == "删除成功") {
          return true
        }
      })
    }
    function random() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    function searchClick(addForm) {
      var tempdata = {
        Id: random(),
        CreateDate: addForm.CreateDate,
        FId: addForm.FId,
        IsDelete: addForm.IsDelete,
        IsUse: addForm.IsUse,
        Name: addForm.Name,
        Remark: addForm.Remark,
        UserId: addForm.UserId,
      }
      addProject(tempdata)
      debugger
      if (tempdata.FId == 0) {
        tableData.value.push(tempdata)
      } else {
        for (var n = 0; n < tableData.value.length; n++) {
          if (tableData.value[n].Id == tempdata.FId) {
            tableData.value[n].children.push(tempdata)
            break
          }
        }
      }
    }
    const addProject = data => {
      AddProject(data).then(response => {
        if (response == "添加成功") {
          handelDialog(false)
        }
      })
    }
    function editClick(editform) {
      EditProject(editform).then(response => {
        if (response == "修改成功") {
          ;("修改成功")
        }
      })
      if (editform.FId == 0) {
        for (var i = 0; i < tableData.value.length; i++) {
          if (editform.Id == tableData.value[i].Id) {
            tableData.value[i] = editform
            if (editform.IsUse == 0) {
              for (var m = 0; m < tableData.value[i].children.length; m++) {
                tableData.value[i].children[m].IsUse = editform.IsUse
                EditProject(tableData.value[i].children[m])
              }
            }

            break
          }
        }
      } else {
        for (var n = 0; n < tableData.value.length; n++) {
          if (editform.FId == tableData.value[n].Id) {
            for (var p = 0; p < tableData.value[n].children.length; p++) {
              if (tableData.value[n].children[p].Id == editform.Id) {
                tableData.value[n].children[p] = editform
                break
              }
            }
          }
        }
      }
      handelDialog(false)
    }
    const resetForm = async () => {
      getDataList()
    }
    onMounted(async () => {
      await getDataList()
      maxHeight(pagination, queryForm, toolBar, ve_max_height)
    })
    return {
      searchClick,
      editClick,
      ProjectEdit,
      detailsForm: {
        Id: "",
        fid: "",
        name: "",
        userid: "",
        createdate: "",
        remark: "",
        status: "",
        follow: "",
        priority: "",
        subject: "",
        assigneuserid: "",
        children: [],
      },
      ve_max_height,
      ve_rowIndex,
      getDataList,
      queryProject,
      tableData,
      params,
      ...{ name, limit, page, total },
      ...{ pagination, queryForm, toolBar },
      ...{ handleEdit, rowData, dialogTitle, IsHidden, ButtonHidden },
      ...{
        onSubmit,
        resetForm,
        handleSizeChange,
        handleCurrentChange,
        rowClassName,
        cellClassName,
        rowClick,
        maxHeight,
      },
      projectList,
      handelDialog,
      handleDel,
      handelSwitch,
      handleEditRoute,
      showDialog,
    }
  },
}
</script>

<style lang="scss" scoped></style>
